package bar.dark.lee.manager.card;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.RadioDialogActivity;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.insert.InsertOutActivity;
import bar.dark.lee.manager.money.BankbookData;
import bar.dark.lee.setting.auto.AutoInsertActivity;

public class CreditCardAddActivity extends SuperActivity
	implements OnClickListener
{
/////////////////////////////////////////////////////////////////
///////////////////		위젯 멤버 변수		/////////////////////
/////////////////////////////////////////////////////////////////
	private static final String PREMONTH = "이전달 "; 
	private static final String NOWMONTH = "이번달 "; 
	private static final String NEXTMONTH = "다음달 ";
	private static final String DAY = "일";

	private static final int REQUEST_END_DATE = 0;
	private static final int REQUEST_RESULT_DATE = 1;
	private static final int REQUEST_BANK = 2;
	
	private Button mBtnAdd;
	private EditText mEditCardName;
	private TextView mTextBankBook;
	private Button mBtnCancel;
	
	private View bankView;
	
	private RadioButton radioNo;
	private RadioButton radioOk;
	
	private View dateView;
	private TextView startDateTextView;
	private TextView endDateTextView;
	private View resultDateView;
	private TextView resultDateTextView;

/////////////////////////////////////////////////////////////////
///////////////////		일반 멤버 변수		/////////////////////
/////////////////////////////////////////////////////////////////
	
	private String mSelectIndex = "";
	private ArrayList<BankbookData> mArrayBankBook;
	private ArrayAdapter<BankbookData> mAdapterBankBook;
	
	private ArrayList<String> dateList = new ArrayList<String>();
	private ArrayList<String> bankList;
	
	// 그 외
	private DBSQLite sql;
	
	private int resultFlag = 1;
	
	private int maxId = -1;

/////////////////////////////////////////////////////////////////
///////////////////		오버라이딩 메소드		/////////////////////
/////////////////////////////////////////////////////////////////

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting_creditcard_add_activity);
		
		sql = DBSQLite.getInstance(this);
		
		setGoneTipButton();
		setTitle("신용카드 추가");
		
		initWidget();
		initListener();
		
		for (int i = 0; i < 31; i++)
		{
			dateList.add((i+1) + "");
		}
		
		new ShowDialog().execute(BDUtil.asyncFlag, 1);
	}
	
	@Override
	public void onClick(View v) {
		if (v == mBtnAdd) 
		{
			if (! (mEditCardName.getText().toString().trim().length() > 0) ) 
			{
				BDUtil.showDialog(this, "확인", "카드이름을 입력해주세요.");
				return;
			} 
			
			if ((Boolean) bankView.getTag() == false)
			{
				BDUtil.showDialog(superContext, "알림", "통장이 하나도 없습니다. 통장부터 만들어주세요.");
				return;
			}
			
			boolean nameOverlap = false;
			
			String cardName = mEditCardName.getText().toString().trim();
			nameOverlap = BDUtil.getOverlapCheck(sql, superContext, 
					"select name from credit_card where name = '" + BDUtil.getApostrophe(cardName) + "';");
			
			if (nameOverlap) 
			{
				BDUtil.showDialog(this, "확인", "동일한 카드 이름이 존재 합니다.");
				return;
			} 
			
			new ShowDialog().execute(BDUtil.asyncFlag, 2);
		} 
		else if (v == mBtnCancel) 
		{
			finish();
		}
		else if (v == dateView)
		{
			Intent intent = new Intent(CreditCardAddActivity.this, RadioDialogActivity.class);
			intent.putExtra(RadioDialogActivity.RADIODATA, dateList);
			
			String selectData = getEndDate();
			
			intent.putExtra(RadioDialogActivity.RADIOSELECT, selectData);
			
			startActivityForResult(intent, REQUEST_END_DATE);
		}
		else if (v == resultDateView)
		{
			Intent intent = new Intent(CreditCardAddActivity.this, RadioDialogActivity.class);
			intent.putExtra(RadioDialogActivity.RADIODATA, dateList);
			
			String selectData = getResultDate();
			
			intent.putExtra(RadioDialogActivity.RADIOSELECT, selectData);
			
			startActivityForResult(intent, REQUEST_RESULT_DATE);
		}
		else if (v == bankView)
		{
			Intent intent = new Intent(superContext, RadioDialogActivity.class);
			intent.putExtra(RadioDialogActivity.RADIODATA, bankList);
			intent.putExtra(RadioDialogActivity.RADIOSELECT, mTextBankBook.getText().toString());
			startActivityForResult(intent, REQUEST_BANK);
		}
	}
	
	private String getStartDate()
	{
		String selectData = startDateTextView.getText().toString().replace(NOWMONTH, "");
		selectData = selectData.replace(PREMONTH, "");
		selectData = selectData.replace(NEXTMONTH, "");
		selectData = selectData.replace(DAY, "");
		
		return selectData;
	}
	
	private String getEndDate()
	{
		String selectData = endDateTextView.getText().toString().replace(NOWMONTH, "");
		selectData = selectData.replace(PREMONTH, "");
		selectData = selectData.replace(NEXTMONTH, "");
		selectData = selectData.replace(DAY, "");
		
		return selectData;
	}
	
	private String getResultDate()
	{
		String selectData = resultDateTextView.getText().toString().replace(NOWMONTH, "");
		selectData = selectData.replace(PREMONTH, "");
		selectData = selectData.replace(NEXTMONTH, "");
		selectData = selectData.replace(DAY, "");
		
		return selectData;
	}

	private void setCreditInsertData()
	{
		mSelectIndex = "";
		
		for (int i = 0; i < mArrayBankBook.size(); i++)
		{
			String name = mArrayBankBook.get(i).getName();
			
			if (mTextBankBook.getText().toString().trim().equals(name))
			{
				mSelectIndex = mArrayBankBook.get(i).getId();
				break;
			}
		}
		
		sql.selectMapTile(this, "SELECT id FROM bankbook WHERE name = '"
				+ BDUtil.getApostrophe(mTextBankBook.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIdx = c.getColumnIndex("id");
				
				c.moveToFirst();
				int id = -1;
				
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
					c.moveToNext();
				}
				
				if (id > -1)
				{
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("name", mEditCardName.getText().toString().trim());
					map.put("banklink", id + "");
					sql.insert(superContext, map, "credit_card");
					
					setCreditDateInsertData();
				}
			}
		});
		
		sql.selectMapTile(superContext, "SELECT id FROM credit_card WHERE name = '"
				+ BDUtil.getApostrophe(mEditCardName.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIdx = c.getColumnIndex("id");
				
				int id = -1;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
					c.moveToNext();
				}
				
				if (id > -1)
				{
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("name", mEditCardName.getText().toString());
					map.put("linkid", id + "");
					map.put("count", "999");
					
					// 세부 체크카드 테이블에 데이터를 셋팅한디.
					sql.insert(superContext, map, "creditcard_detail");
				}
			}
		});
	}
	
	private boolean setCreditDateInsertData()
	{
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("name", mEditCardName.getText().toString().trim());
		map.put("linkname", mTextBankBook.getText().toString());
		
		if (radioNo.isChecked())
		{
			map.put("autoyn", "2");
		}
		else
		{
			map.put("autoyn", "1");
		}
		
		map.put("startdate", getStartDate());
		map.put("enddate", getEndDate());
		map.put("resultdate", getResultDate());
		
		Calendar cal = Calendar.getInstance();
		
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH)+1;
		int day = Integer.parseInt(getResultDate());
		
		if (day >= cal.get(Calendar.DAY_OF_MONTH))
		{
			if (month == 1)
			{
				year--;
				month = 12;
			}
			else 
			{
				month--;
			}
		}
		
		map.put("signdate", BDUtil.getDateDB(year, month, day));
		
		if (resultFlag == 1)
		{
			map.put("resultflag", "1");
		}
		else
		{
			map.put("resultflag", "2");
		}
		
		sql.selectMapTile(this, "SELECT max(id) maxid FROM credit_card;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int maxIdIdx = c.getColumnIndex("maxid");
				
				c.moveToFirst();
				
				maxId = -1;
				
				for (int i = 0; i < c.getCount(); i++)
				{
					maxId = c.getInt(maxIdIdx);
					c.moveToNext();
				}
			}
		});
		
		if (maxId < 0)
		{
			return false;
		}
		
		map.put("linkid", maxId + "");
		
		sql.insert(this, map, "credit_card_result_date");
		
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode == Activity.RESULT_OK)
		{
			if (requestCode == REQUEST_END_DATE)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				
				int endDate = Integer.parseInt(selectData);
				int resultDate = Integer.parseInt(getResultDate());
				int startDate = Integer.parseInt(selectData)+1;
				
				if (resultDate > endDate)
				{
					resultFlag = 1;
					resultDateTextView.setText(NOWMONTH + resultDate + DAY);
				}
				else if (resultDate < endDate)
				{
					resultFlag = 2;
					resultDateTextView.setText(NEXTMONTH + resultDate + DAY);
				}
				else if (resultDate == endDate)
				{
					BDUtil.showDialog(this, "경고", "적용 마지막 날짜와 결제일은 같은 날을 할수 없습니다.");
					return;
				}
				
				endDateTextView.setText(NOWMONTH + selectData + DAY);
				
				if (endDate == 31)
				{
					startDate = 1;
					startDateTextView.setText(NOWMONTH + startDate + DAY);
				}
				else
				{
					startDateTextView.setText(PREMONTH + startDate + DAY);
				}
			}
			else if (requestCode == REQUEST_RESULT_DATE)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				
				int endDate = Integer.parseInt(getEndDate());
				int resultDate = Integer.parseInt(selectData);
				
				if (resultDate > endDate)
				{
					resultFlag =1;
					resultDateTextView.setText(NOWMONTH + selectData + DAY);
				}
				else if (resultDate < endDate)
				{
					resultFlag = 2;
					resultDateTextView.setText(NEXTMONTH + selectData + DAY);
				}
				else if (resultDate == endDate)
				{
					BDUtil.showDialog(this, "경고", "적용 마지막 날짜와 결제일은 같은 날을 할수 없습니다.");
				}
				
			}
			else if (requestCode == REQUEST_BANK)
			{
				if (resultCode == Activity.RESULT_OK)
				{
					String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
					mTextBankBook.setText(selectData);
				}
			}
		}
	}

/////////////////////////////////////////////////////////////////
///////////////////			일반 메소드		/////////////////////
/////////////////////////////////////////////////////////////////

	/**
	* 위젯 초기화
	*/
	private void initWidget() {
		mBtnAdd = (Button)findViewById(R.id.SETTING_CREDITCARD_ADD_btnAdd);
		mBtnCancel = (Button)findViewById(R.id.SETTING_CREDITCARD_ADD_btnCancel);
		mEditCardName = (EditText)findViewById(R.id.SETTING_CREDITCARD_ADD_editName);
		mTextBankBook = (TextView)findViewById(R.id.SETTING_CREDITCARD_ADD_textBankbookName);
		
		bankView = findViewById(R.id.creditInsertBankView);
		
		radioNo = (RadioButton) findViewById(R.id.creditInsertRadioNo);
		radioOk = (RadioButton) findViewById(R.id.creditInsertRadioOk);
		
		dateView = findViewById(R.id.creditInsertDateView);
		startDateTextView = (TextView)findViewById(R.id.creditInsertStartDateTextView);
		endDateTextView = (TextView)findViewById(R.id.creditInsertEndDateTextView);
		resultDateView = findViewById(R.id.creditInsertResultDateView);
		resultDateTextView = (TextView)findViewById(R.id.creditInsertResultDateTextView);
	}
	
	/**
	* 리스너 초기화
	*/
	private void initListener() {
		mBtnAdd.setOnClickListener(this);
		mBtnCancel.setOnClickListener(this);
		
		dateView.setOnClickListener(this);
		resultDateView.setOnClickListener(this);
		
		bankView.setOnClickListener(this);
	}

	/**
	 * 통장 데이터 가져온다
	 */
	private void getBankBookData() 
	{
		mArrayBankBook = new ArrayList<BankbookData>();
		bankList = new ArrayList<String>();
		
		sql.selectMapTile(this, "SELECT id, name, money FROM bankbook;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				c.moveToFirst();
				
				int idIndex = c.getColumnIndex("id");
				int nameIndex = c.getColumnIndex("name");
				int moneyIndex = c.getColumnIndex("money");
				
				for (int i = 0; i < count; i++)
				{
					BankbookData data = new BankbookData();
					data.setId(c.getString(idIndex));
					data.setName(c.getString(nameIndex));
					data.setMoney(c.getString(moneyIndex));
					mArrayBankBook.add(data);
					bankList.add(data.getName());
					c.moveToNext();
				}
			}
		});
	}

	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(CreditCardAddActivity.this);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0) {
				if (arg0[1] == 1)
				{
					getBankBookData();
					
					return arg0[1];
				}
				else if (arg0[1] == 2)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setCreditInsertData();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				return arg0[0];
			} else 
				return arg0[0];
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 1)
			{
				if (mArrayBankBook.size() < 1)
				{
					String memo = "없음";
					bankList.add(memo);
					bankView.setClickable(false);
					bankView.setTag(false);
				}
				else
				{
					bankView.setClickable(true);
					bankView.setTag(true);
				}
				
				mTextBankBook.setText(bankList.get(0).toString());
				
				startDateTextView.setText(PREMONTH + dateList.get(1) + DAY);
				endDateTextView.setText(NOWMONTH + dateList.get(0) + DAY);
				resultDateTextView.setText(NOWMONTH + dateList.get(2) + DAY);
				resultFlag = 1;
				
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
			}
			else if (result == 2)
			{
				BDUtil.showDialogFinish(CreditCardAddActivity.this, "확인", "신용카드가 추가 되었습니다.");
			}
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
